package com.github.kezhenxu94.playground.java.miscellaneous;

public class FinalizeEscapeGC {

	public static FinalizeEscapeGC SAVE_HOOK = null;

	public void isAlive() {
		System.out.println("ALIVE");
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		System.out.println("FINALIZE");
		FinalizeEscapeGC.SAVE_HOOK = this;
	}

	public static void main(String[] args) throws Throwable {
		SAVE_HOOK = new FinalizeEscapeGC();
		// 对象第一次自救
		SAVE_HOOK = null;
		System.gc();

		Thread.sleep(500);
		if (SAVE_HOOK != null)
			SAVE_HOOK.isAlive();
		else
			System.out.println("DEAD");

		SAVE_HOOK = null;
		// 自救失败
		System.gc();
		Thread.sleep(500);

		if (SAVE_HOOK != null)
			SAVE_HOOK.isAlive();
		else
			System.out.println("DEAD");

	}
}
